<?
/* $Id: str.php 56 2011-02-22 10:52:48Z jim2212001@gmail.com $ */
if(!defined('WEBHOME'))
	die ('DO NOT EXECUTE THIS FILE');
function escape_all(&$array){
	global $db;
	foreach($array as &$value){
		$value = $db->real_escape_string($value);
	}
}
function between($check,$min,$max){
	return !($check>$max || $check<$min);
}
function mb_checkLength($str,$min,$max){
	return between(mb_strlen($str),$min,$max);
}
function checkLength($str,$min,$max){
	return between(strlen(str),$min,$max);
}
function validLink($link) {
    if(preg_match("/(http|https):\/\//", $link)) {
        return true;
    } else {
        return false;
    }
}
function ajaxValidate(&$res,$data,$rule){
/* $rule format
array of following
array(
	  'type'=>('length'|'int'|'link'),
	  'field'=>FIELD_NAME,
	  'min'=>MIN_LENGTH, 	// Required for type length. Optional for type int.
	  'max'=>MAX_LENGTH,	// Required for type length. Optional for type int.
	  [optional=>IS_OPTIONAL]//will not do validation if null
*/
	foreach($rule as $v){
		$res['type']=$v['type'];
		$res['field']=$v['field'];
		if(isset($v['optional']) && $v['optional'] && $data[$v['field']]=='')
			continue;
		if($v['type']=='length'){
			if(!mb_checkLength($data[$v['field']],$v['min'],$v['max'])){
				$res['min']=$v['min'];
				$res['max']=$v['max'];
				exit(json_encode($res));
			}
		}elseif($v['type']=='int'){
			if(!isset($v['min']))
				$v['min']=$data[$v['field']];
			else
				$res['min']=$v['min'];
			if(!isset($v['max']))
				$v['max']=$data[$v['field']];
			else
				$res['max']=$v['max'];
			if(!is_numeric($data[$v['field']]) || $data[$v['field']]>$v['max'] || $data[$v['field']]<$v['min']){
				exit(json_encode($res));
			}
			// avoid confusing other rules.
			unset($res['min'],$res['max']);
		}elseif($v['type']=='link'){
			if(!validLink($data[$v['field']])){
				exit(json_encode($res));
			}
		}
	}
}
?>
